// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.LoanMonthlyBalance;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.LoanMonthlyBalanceMapper;
import com.fowo.api.model.loan.monthly.balance.LoanMonthlyBalanceBatchFinishRequestPayoutAction;
import com.fowo.api.model.loan.monthly.balance.LoanMonthlyBalanceExcelPo;
import com.fowo.api.model.loan.monthly.balance.LoanMonthlyBalanceFinishRequestPayoutAction;
import com.fowo.api.model.loan.monthly.balance.LoanMonthlyBalanceItemVo;
import com.fowo.api.model.loan.monthly.balance.LoanMonthlyBalanceSearchParamPo;
import com.fowo.api.model.loan.monthly.balance.LoanMonthlyBalanceVo;
import com.fowo.api.service.LoanMonthlyBalanceService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 货款月结 服务实现基类
 * @author 蜂窝蜜造平台 配置人：李玉娇，沈友谅
 */
@Slf4j
@DataObjectType(LoanMonthlyBalance.class)
@DS("ds24")
public class LoanMonthlyBalanceBaseServiceImpl
  extends ServiceImpl<LoanMonthlyBalanceMapper, LoanMonthlyBalance>
  implements LoanMonthlyBalanceService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("supplierNameSupplierName", "s.`supplier_name`");
      put("applicationDepName", "sd.`name`");
      put("widName", "w.`name`");
      put("stockinUidName", "su.`name`");
      put("optUidName", "su2.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected LoanMonthlyBalanceService self;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected LoanMonthlyBalanceFinishRequestPayoutAction loanMonthlyBalanceFinishRequestPayoutAction;

  @Autowired(required = false)
  protected LoanMonthlyBalanceBatchFinishRequestPayoutAction loanMonthlyBalanceBatchFinishRequestPayoutAction;

  @Resource
  protected Validator validator;

  /**
   * 创建货款月结
   * @param model 货款月结
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(LoanMonthlyBalanceVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LoanMonthlyBalance entity = new LoanMonthlyBalance();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("10");
    }

    if (model.getPayType() == null) {
      entity.setPayType("ZF01");
    }

    if (model.getCurrency() == null) {
      entity.setCurrency("CNY");
    }

    if (model.getWithdrawDimension() == null) {
      entity.setWithdrawDimension("20");
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("货款月结保存失败");
  }

  /**
   * 更新货款月结
   * @param model 货款月结
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(LoanMonthlyBalanceVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LoanMonthlyBalance entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("货款月结不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新货款月结（带空值）
   * @param model 货款月结
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(LoanMonthlyBalanceVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LoanMonthlyBalance entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("货款月结不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(LoanMonthlyBalance::getSupplierName, model.getSupplierName())
      .set(LoanMonthlyBalance::getDescribe, model.getDescribe())
      .set(LoanMonthlyBalance::getLastUpdateTime, model.getLastUpdateTime())
      .set(LoanMonthlyBalance::getLastUpdateUser, model.getLastUpdateUser())
      .set(LoanMonthlyBalance::getBudgetRatio, model.getBudgetRatio())
      .set(LoanMonthlyBalance::getPredictFkTime, model.getPredictFkTime())
      .set(LoanMonthlyBalance::getPayType, model.getPayType())
      .set(LoanMonthlyBalance::getUserName, model.getUserName())
      .set(LoanMonthlyBalance::getBankOfDeposit, model.getBankOfDeposit())
      .set(LoanMonthlyBalance::getAccount, model.getAccount())
      .set(LoanMonthlyBalance::getCurrency, model.getCurrency())
      .set(LoanMonthlyBalance::getRemarks, model.getRemarks())
      .set(
        model.getFiles() != null,
        LoanMonthlyBalance::getFiles,
        JSON.toJSONString(model.getFiles())
      )
      .setSql(model.getFiles() == null, "files = null")
      .eq(LoanMonthlyBalance::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    return false;
  }

  /**
   * 删除货款月结
   * @param id 货款月结的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除货款月结
   * @param ids 货款月结的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    LoanMonthlyBalanceSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "supplierName",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((LoanMonthlyBalanceItemVo) r).getSupplierNameSupplierName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "applicationDep",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((LoanMonthlyBalanceItemVo) r).getApplicationDepName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "wid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((LoanMonthlyBalanceItemVo) r).getWidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "warehousingDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "closingPeriod",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "dueDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00079")
      );
      exportOptions.addFieldMappingOption(
        "withdrawDimension",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00080")
      );
      exportOptions.addFieldMappingOption(
        "stockinUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((LoanMonthlyBalanceItemVo) r).getStockinUidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "optUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((LoanMonthlyBalanceItemVo) r).getOptUidName())
          )
      );
      exportOptions.addStringFields(
        "supplierNameSupplierName",
        "purchaseOrderCode",
        "applicationDepName",
        "orderSn",
        "widName",
        "status",
        "withdrawDimension",
        "qkSn",
        "stockinUidName",
        "optUidName"
      );

      String fileName = String.format(
        "货款月结(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00079");
    List<SysDictAllItem> withdrawDimensionItems = sysDictService.getDictItems(
      "SCM00080"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<LoanMonthlyBalanceExcelPo> items =
      new ArrayList<LoanMonthlyBalanceExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<LoanMonthlyBalanceItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<LoanMonthlyBalanceItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (LoanMonthlyBalanceItemVo item : list) {
        LoanMonthlyBalanceExcelPo excel = new LoanMonthlyBalanceExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        if (item.getWithdrawDimension() != null) {
          withdrawDimensionItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getWithdrawDimension()))
            .findFirst()
            .ifPresent(i -> excel.setWithdrawDimension(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "货款月结(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(LoanMonthlyBalanceExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过采购单号查询货款月结主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByPurchaseOrderCode(String purchaseOrderCode) {
    return this.baseMapper.getIdByPurchaseOrderCode(purchaseOrderCode);
  }

  /**
   * 通过采购单号查询货款月结多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByPurchaseOrderCode(List<String> list) {
    return this.baseMapper.getIdsByPurchaseOrderCode(list);
  }

  /**
   * 通过货款月结主键查询采购单号
   */
  @Override
  public String getPurchaseOrderCodeById(Long id) {
    return this.baseMapper.getPurchaseOrderCodeById(id);
  }

  /**
   * 通过货款月结主键查询采购单号列表
   */
  @Override
  public List<String> getPurchaseOrderCodeByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getPurchaseOrderCodeByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("purchaseOrderCode")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 货款月结的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public LoanMonthlyBalanceVo getVoById(Long id) throws Exception {
    LoanMonthlyBalanceVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询货款月结
   * @param search 查询条件
   * @return 货款月结分页查询结果
   */
  @Override
  public Page<LoanMonthlyBalanceItemVo> pageSearch(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    Page<LoanMonthlyBalanceItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(LoanMonthlyBalanceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 货款月结快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'LoanMonthlyBalanceOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<LoanMonthlyBalanceItemVo>> searchOptions(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询货款月结
   * @param search 查询条件
   * @return 货款月结列表查询结果
   */
  @Override
  public List<LoanMonthlyBalanceItemVo> search(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询货款月结最后更新时间
   * @param search 查询条件
   * @return 货款月结最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(LoanMonthlyBalanceSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 结束请款
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了结束请款操作"
  )
  @Override
  public void finishRequestPayout(Long id) throws Exception {
    if (loanMonthlyBalanceFinishRequestPayoutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    loanMonthlyBalanceFinishRequestPayoutAction.run(id);
  }

  /**
   * 结束请款
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了结束请款操作"
  )
  @Override
  public void batchFinishRequestPayout(List<Long> ids) throws Exception {
    if (loanMonthlyBalanceBatchFinishRequestPayoutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    loanMonthlyBalanceBatchFinishRequestPayoutAction.run(ids);
  }

  /**
   * 全部
   */
  @Override
  public List<LoanMonthlyBalanceItemVo> allmonthly(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allmonthly(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<LoanMonthlyBalanceItemVo> allmonthlyPage(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    Page<LoanMonthlyBalanceItemVo> allmonthlyPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allmonthlyPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allmonthlyPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allmonthlyPage =
      this.baseMapper.allmonthlyPage(
          search.toPage(this.baseMapper.allmonthlyCount(search)),
          search
        );
    List<Long> recordIds = allmonthlyPage
      .getRecords()
      .stream()
      .map(LoanMonthlyBalanceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allmonthlyPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allmonthlyPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allmonthlyPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allmonthlyPage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allmonthlyLastUpdateTime(LoanMonthlyBalanceSearchParamPo search) {
    return this.baseMapper.allmonthlyLastUpdateTime(search);
  }

  /**
   * 待申请
   */
  @Override
  public List<LoanMonthlyBalanceItemVo> waitApply(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitApply(search);
  }

  /**
   * 待申请分页
   */
  @Override
  public Page<LoanMonthlyBalanceItemVo> waitApplyPage(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    Page<LoanMonthlyBalanceItemVo> waitApplyPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitApplyPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitApplyPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitApplyPage =
      this.baseMapper.waitApplyPage(
          search.toPage(this.baseMapper.waitApplyCount(search)),
          search
        );
    List<Long> recordIds = waitApplyPage
      .getRecords()
      .stream()
      .map(LoanMonthlyBalanceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitApplyPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitApplyPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitApplyPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitApplyPage;
  }

  /**
   * 查询待申请最后更新时间
   * @param search 查询条件
   * @return 待申请最后更新时间
   */
  @Override
  public Date waitApplyLastUpdateTime(LoanMonthlyBalanceSearchParamPo search) {
    return this.baseMapper.waitApplyLastUpdateTime(search);
  }

  /**
   * 全额申请
   */
  @Override
  public List<LoanMonthlyBalanceItemVo> infullApply(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.infullApply(search);
  }

  /**
   * 全额申请分页
   */
  @Override
  public Page<LoanMonthlyBalanceItemVo> infullApplyPage(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    Page<LoanMonthlyBalanceItemVo> infullApplyPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return infullApplyPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return infullApplyPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    infullApplyPage =
      this.baseMapper.infullApplyPage(
          search.toPage(this.baseMapper.infullApplyCount(search)),
          search
        );
    List<Long> recordIds = infullApplyPage
      .getRecords()
      .stream()
      .map(LoanMonthlyBalanceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return infullApplyPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return infullApplyPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    infullApplyPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return infullApplyPage;
  }

  /**
   * 查询全额申请最后更新时间
   * @param search 查询条件
   * @return 全额申请最后更新时间
   */
  @Override
  public Date infullApplyLastUpdateTime(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    return this.baseMapper.infullApplyLastUpdateTime(search);
  }

  /**
   * 已付清
   */
  @Override
  public List<LoanMonthlyBalanceItemVo> paidOff(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.paidOff(search);
  }

  /**
   * 已付清分页
   */
  @Override
  public Page<LoanMonthlyBalanceItemVo> paidOffPage(
    LoanMonthlyBalanceSearchParamPo search
  ) {
    Page<LoanMonthlyBalanceItemVo> paidOffPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return paidOffPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return paidOffPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    paidOffPage =
      this.baseMapper.paidOffPage(
          search.toPage(this.baseMapper.paidOffCount(search)),
          search
        );
    List<Long> recordIds = paidOffPage
      .getRecords()
      .stream()
      .map(LoanMonthlyBalanceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return paidOffPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return paidOffPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    paidOffPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return paidOffPage;
  }

  /**
   * 查询已付清最后更新时间
   * @param search 查询条件
   * @return 已付清最后更新时间
   */
  @Override
  public Date paidOffLastUpdateTime(LoanMonthlyBalanceSearchParamPo search) {
    return this.baseMapper.paidOffLastUpdateTime(search);
  }
}
